<template>
  <div class="shopCar">
    <van-nav-bar title="购物车" left-text="返回" left-arrow @click-left="back">
      <template #right>
        <div @click="toggleEdit" v-if="shopData.length > 0">
          {{ !edit ? "编辑" : "完成" }}
        </div>
      </template>
    </van-nav-bar>
    <div v-if="shopData.length > 0" class="contain">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="我是有底线的"
        offset="100"
        @load="loadShopData"
      >
        <van-swipe-cell
          class="shopCell"
          :disabled="edit"
          v-for="(item, index) in shopData"
          :key="item.sid"
        >
          <div class="shopItem">
            <div class="check">
              <van-checkbox
                v-model="item.isChecked"
                icon-size="20px"
                @change="onlySelect"
              ></van-checkbox>
            </div>
            <div class="goods">
              <div class="goodsImg">
                <img :src="item.small_img" />
              </div>
              <div class="goodsDescription">
                <div class="description">
                  <div class="mainInfo">
                    <div class="name">{{ item.name }}</div>
                    <div class="rule">{{ item.rule }}</div>
                  </div>
                  <div class="enname">{{ item.enname }}</div>
                </div>
                <div class="countBox">
                  <div class="price">&yen;{{ item.price }}</div>
                  <div class="count">
                    <van-stepper
                      v-model="item.count"
                      theme="round"
                      button-size="22"
                      disable-input
                      @change="updateShopCount(item.sid, item.count)"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <template #right>
            <van-button
              square
              text="删除"
              class="delete"
              color="#CC9145"
              type="danger"
              @click="deleteShopCar([item.sid], index)"
            />
          </template>
        </van-swipe-cell>
      </van-list>
    </div>
    <van-submit-bar
      v-show="!edit"
      :price="total"
      button-text="提交订单"
      button-color="#CC9145"
      @submit="commit"
    >
      <van-checkbox v-model="allCheck" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>
    <van-submit-bar
      v-show="edit"
      :price="total"
      button-text="删除选择"
      button-color="#CC9145"
      @submit="deleteSelect"
    >
      <van-checkbox v-model="allCheck" @click="allSelect">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
import "../assets/less/shopCar.less";
import { mapState, mapMutations } from "vuex";
export default {
  name: "ShopCar",
  data() {
    return {
      edit: false,
      allCheck: false,
      allShopData: [],
      shopData: [],
      start: 0,
      count: 6,
      loading: true,
      finshed: false,
      total: 0,
      commitData: [],
    };
  },
  created() {
    this.getShopCarData();
  },
  methods: {
    ...mapMutations(["changeShopCount"]),

    toggleEdit() {
      this.edit = !this.edit;
    },

    getShopCarData() {
      let tokenString = this.$cookies.get("tokenString");

      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中",
        forbidClick: true,
        duration: 0,
      });

      this.$axios({
        method: "GET",
        url: "/findAllShopcart",
        params: {
          appkey: this.appkey,
          tokenString,
        },
      })
        .then((res) => {
          // console.log("res getShopCarData ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 5000) {
            res.data.result.forEach((v) => {
              v.isChecked = false;
            });

            this.allShopData = res.data.result;

            this.shopData = this.allShopData.slice(
              this.start,
              this.start + this.count
            );

            this.start += this.count;

            if (this.allShopData.length < this.count) {
              this.finished = true;
              return;
            }
            this.loading = false;
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    loadShopData() {
      setTimeout(() => {
        let data = this.allShopData.slice(this.start, this.start + this.count);

        this.shopData.push(...data);

        this.start += this.count;

        if (data.length > 0) {
          this.allCheck = false;
        }

        if (data.length < this.count) {
          console.log("已经加载完毕数据");
          this.finished = true;
          return;
        }
        this.loading = false;
      }, 1000);
    },
    updateShopCount(sid, count) {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中",
        forbidClick: true,
        duration: 0,
      });
      this.$axios({
        method: "POST",
        url: "/modifyShopcartCount",
        data: {
          appkey: this.appkey,
          tokenString,
          sid,
          count,
        },
      })
        .then((res) => {
          // console.log("res updateShopCount ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code === 6000) {
            this.sum();
          } else {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
          }
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    deleteShopCar(sids, index) {
      let tokenString = this.$cookies.get("tokenString");
      if (!tokenString) {
        return this.$router.push({ name: "Login" });
      }
      this.$toast.loading({
        message: "加载中",
        forbidClick: true,
        duration: 0,
      });
      this.$axios({
        method: "POST",
        url: "/deleteShopcart",
        data: {
          appkey: this.appkey,
          tokenString,
          sids: JSON.stringify(sids),
        },
      })
        .then((res) => {
          // console.log("res removeSopCar ==> ", res);
          this.$toast.clear();

          if (res.data.code == 700) {
            this.$toast({
              message: res.data.msg,
              forbidClick: true,
              duration: 1000,
            });
            return this.$router.push({ name: "Login" });
          }

          if (res.data.code == 7000) {
            if (index !== undefined) {
              this.shopData.splice(index, 1);

              this.changeShopCount(this.shopCount - 1);

              this.onlySelect();
            } else {
              for (let i = 0; i < this.shopData.length; i++) {
                if (this.shopData[i].isChecked) {
                  this.shopData.splice(i, 1);
                  i--;
                }
              }

              this.changeShopCount(this.shopCount - sids.length);
              this.sum();
            }

            this.$nextTick(() => {
              let cells = document.querySelectorAll(".shopCell");

              console.log("cells ==> ", cells);

              if (
                cells.length === 0 &&
                this.shopData.length < this.allShopData.length
              ) {
                this.loadShopData();
              } else {
                let cellSzie = cells[cells.length - 1].getBoundingClientRect();

                let distance = cellSzie.top;

                let cellHeight = cellSzie.height;

                let innerHeight = window.innerHeight;

                if (distance + cellHeight - innerHeight <= 50) {
                  this.loadShopData();
                }
              }
            });
          }

          this.$toast({
            message: res.data.msg,
            forbidClick: true,
            duration: 1000,
          });
        })
        .catch((err) => {
          this.$toast.clear();
          console.log("err ==> ", err);
        });
    },
    deleteSelect() {
      let sids = [];
      this.shopData.forEach((v) => {
        if (v.isChecked) {
          sids.push(v.sid);
        }
      });

      if (sids.length === 0) {
        this.$toast({
          message: "未选择删除商品",
          forbidClick: true,
          duration: 1000,
        });

        return;
      }

      console.log("sids ==> ", sids);

      this.deleteShopCar(sids);
    },
    onlySelect() {
      this.sum();

      for (let i = 0; i < this.shopData.length; i++) {
        if (!this.shopData[i].isChecked) {
          this.allCheck = false;
          return;
        }
      }

      this.allCheck = true;
    },
    allSelect() {
      this.shopData.forEach((v) => {
        v.isChecked = this.allCheck;
      });

      this.sum();
    },
    sum() {
      let totalPrice = 0;
      this.shopData.forEach((v) => {
        if (v.isChecked) {
          totalPrice += v.price * v.count;
        }
      });

      this.total = totalPrice * 100;
    },
    back() {
      this.$router.go(-1);
    },
    commit() {
      let sids = [];
      this.shopData.forEach((ele) => {
        if (ele.isChecked) {
          sids.push(ele.sid);
        }
      });
      if (sids.length === 0) {
        this.$toast({
          message: "选择下单的商品",
          forbidClick: true,
          duration: 1000,
        });
        return;
      }
      this.$router.push({ name: "Commit", query: { sids: sids.join(",") } });
    },
  },
  computed: {
    ...mapState(["shopCount"]),
  },
};
</script>

<style lang="less" scoped>
</style>